package sample.web;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import sample.analysis.util.FileCopyUtil;
import sample.controller.MyController;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.ResultSet;

public class SavaToReport implements HttpHandler {
    @Override
    public void handle(HttpExchange xchg) throws IOException {

        //获取文件夹名称
        String header_name = xchg.getRequestURI().getQuery();
        String ip = sample.util.IpRegEx.getIps(header_name).get(0).toString();
        header_name = header_name.substring(ip.length()+1,header_name.length()-5);

        //导出报告
        FileCopyUtil fileCopyUtil = new FileCopyUtil();
        String putfilepath = MyController.properties.getProperty("reportPath")+File.separator+header_name;
        fileCopyUtil.copyDir(new File("").getAbsolutePath()+File.separator+"dist",putfilepath);

        //导出完，记录报告路径
        //更新解析信息入库和表格展示
        //数据库连接
        sample.controller.MyController.h2dbCRUDUtil.insertOrUpdateSql("UPDATE nmonMonitorList_table SET toLink = '"+putfilepath+"' WHERE nmonName like '%"+header_name+"%'");
        ResultSet resultSet = sample.controller.MyController.h2dbCRUDUtil.selectSql("Select id from nmonMonitorList_table where nmonName like '%"+header_name+"%'");
        try {
            while (resultSet.next()){
//                                        System.out.println(resultSet.getInt("id"));
                sample.controller.MyController.monitorHistoryDataList.get(resultSet.getInt("id")-1).setToLink(putfilepath);
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

        xchg.sendResponseHeaders(200,0);
        OutputStream os = xchg.getResponseBody();
        String response = "导出完成";
        os.write(response.getBytes());
        os.close();
    }
}
